﻿using System;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using Data;
using Models;
namespace Web.Controllers
{
    public class AuthController : BaseController
    {
        //
        // GET: /auth/

        public ActionResult Index()
        {
            
            var existingCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
            return existingCookie != null ? View("allreadyLogged") : View();
        }


        [HttpPost]
        public ActionResult Index(Users user)
        {
            if (ModelState.IsValid)
            {
                var dbUsers = new UsersData();

                var usersList = dbUsers.GetUsers(login:user.Login);

                if(usersList != null)
                {
                    if(user.Pwd == usersList[0].Pwd)
                    {
                        var ticket = new FormsAuthenticationTicket(1,
                                                            user.Login,
                                                            DateTime.Now,
                                                            DateTime.Now.AddDays(1),
                                                            true,
                                                            Convert.ToString(usersList[0].Role),
                                                            FormsAuthentication.FormsCookiePath
                                                            );
                        var encTicket = FormsAuthentication.Encrypt(ticket);
                        HttpContext.Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encTicket));
                        return View("Logged");
                    }
                }
            }
           
            return View(user);
        }


        public ActionResult LogOut()
        {
            var existcookie = Request.Cookies[FormsAuthentication.FormsCookieName];

            if (existcookie != null)
            {
                existcookie.Expires = DateTime.Now.AddDays(-1);
                Response.Cookies.Add(existcookie);
            }
           
            return Redirect("/home");
        }

    }
}
